<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ShopProduct\ShopProductDeleteAction;
use App\Admin\Actions\ShopProduct\ShopProductDownStatusAction;
use App\Admin\Actions\ShopProduct\ShopProductUpStatusAction;
use App\Admin\Grid\Tools\ShopProduct\AllShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\SaleShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\UnSaleShopProductTools;
use App\Library\Logic\ShopProductSpecsLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Models\AdminShopProductModel;
use App\Library\Traits\AdminControllerTrait;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Grid\Tools;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class ShopProductHelpController extends AdminController
{
    use AdminControllerTrait;

    protected $title = '助力';

    /**
     * grid
     * @return Grid
     */
    protected function grid(): Grid
    {
        $grid = new Grid(new AdminShopProductModel);
        $grid
            ->model()->with('specs')
            ->leftJoin('shop_product_ext', 'shop_product_ext.product_id', 'shop_product.product_id')
            ->where('is_help', 1)
            ->orderByDesc('product_id')
            ->select('shop_product.*');
        $status = request()->get('status');
        if (!is_null($status)) {
            $status = match ((int) $status) {
                0 => 1,
                1 => 2,
                default => -1
            };
            $grid->model()->where('product_status', $status);
        }
        $grid->filter(function (Filter $filter,) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Filter $filter,) {
                $filter->equal('shop_product-product_id', 'ID')->integer();
            });
            $filter->column(1 / 2, function (Filter $filter,) {
                $filter->equal('serial_number', __('l.serialNumber'));
            });
        });
        $grid->column('product_id', 'ID')->sortable();
        $grid->column('serial_number', __('l.serialNumber'));
        $grid->column('product_status', '状态')->using(__('shop_product.productStatusArr'));
        $grid->column('status_recommend', '推荐')->using(__('l.whether'));
        $grid->column('sort', __('l.sort'))->sortable();
        $grid->column('product_avatar', '图片')->display(function ($column,) {
            if (!is_null($column)) {
                return view('image', ['id' => $this->product_id, 'image' => fileIdToUrl($column)]);
            } else {
                return null;
            }
        });
        $grid->column('product_name', '名称')->display(function ($column,) {
            if (strlen($column) > 20) {
                return mb_substr($column, 0, 20).'...';
            } else {
                return $column;
            }
        });
        $specSimple = $this->specSimple();
        $grid->column('spec', '规格')->expand(function ($model,) use ($specSimple) {
            return new Table(
                array_values($specSimple), $model->specs->map(function ($spec,) use ($specSimple) {
                if (!empty($spec->ps_avatar)) {
                    $spec->fileUrl = view('image', [
                        'size' => 50,
                        'id' => $spec->serial_number,
                        'image' => fileIdToUrl($spec->ps_avatar),
                    ]);
                }
                return $spec->only(array_keys($specSimple));
            })->toArray(),
            );
        })->style('text-align:center');
        $grid->tools(function (Tools $tools,) use ($status) {
            $collection = AdminShopProductModel::query()->where('is_help', 1)->groupBy('product_status')
                ->pluck(DB::raw('count(*) as count'), 'product_status');
            $as = request()->route()->action['as'];;
            $tools->append(new AllShopProductTools($status ?? 0, $as));
            $tools->append(new SaleShopProductTools($collection[2] ?? 0, $status ?? 0, $as));
            $tools->append(new UnSaleShopProductTools($collection[1] ?? 0, $status ?? 0, $as));
        });
        $grid->disableActions(false);
        $grid->disableCreateButton(false);
        $grid->actions(function (Actions $action) {
            if ($action->row->product_status === 1) {
                $action->add(new ShopProductDeleteAction);
                $action->add(new ShopProductUpStatusAction);
            } else {
                $action->add(new ShopProductDownStatusAction);
                $action->disableEdit();
            }
            $action->disableDelete();
        });
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new AdminShopProductModel);
        $form->hidden('is_help')->default(1);
        $form->hidden('product_id');
        $form->hidden('product_category_id_1')->default(1);
        $form->hidden('product_category_id_2');
        $form->hidden('product_category_id_3');
        $form->hidden('main_img_ids');
        $form->hidden('desc_img_ids');
        $form->hidden('min_price');
        $form->hidden('video_id');
        $form->hidden('publish_at');
        $form->hidden('product_avatar');
        $form->hidden('ossPrefix')->default(config('oss.url'));
        if ($form->isCreating()) {
            $form->hidden('serial_number');
            $form->hidden('add_user_id')->default(Admin::user()->user_id);
            $form->hidden('user_id')->default(Admin::user()->user_id);
            $form->hidden('created_time');
        }
        $form->ignore(['ossPrefix']);
        $item = $this->item($form);
        $form->column(1 / 2, function (Form $form,) use ($item) {
            $form->display('mainImgIds', __('l.mainImgIds'))->with(function () use ($item) {
                return view('upload_main_imgs', [
                    'mainImgStr' => AdminShopProductModel::mainImgStr($item),
                ]);
            });
            $form
                ->select('ext.plug_cate', '分类')->default(1)->options(Arr::get(cache('systemConfig:1'), 'jlTag'))
                ->rules('required')->required();
            $form
                ->text('product_name', __('l.title'))->attribute('maxlength', 30)->default(random())
                ->rules('required')->required();
            $form->tags('product_gene', __('shop_product.gene'))->options(explode(',', __('shop_product.geneStr')));
            $form->textarea('product_note', __('shop_product.product_note'));
            $form->display('descImgIds', __('l.descImgIds'))->with(function () use ($form, $item) {
                return view('upload_desc_imgs', [
                    'descImgStr' => AdminShopProductModel::descImgStr($item),
                ]);
            });
        });
        $form->column(1 / 2, function (Form $form,) use ($item) {
            $form->display('video', __('l.video'))->with(function () use ($item) {
                return view('upload_video', [
                    'videoStr' => AdminShopProductModel::videoStr($item),
                ]);
            });
            $form
                ->select('product_status', __('shop_product.productStatus'))->default(2)
                ->options(__('shop_product.productStatusArr'))->rules('required')->required();
            $form->tags('product_label', __('l.tag'));
            $form->select('product_stage', __('shop_product.stage'))->options(__('shop_product.stageArr'));
            $form
                ->currency('max_price', '原价')->attribute('maxlength', 8)->symbol('￥')
                ->rules('required|min:0')->required();
            $form
                ->currency('ext.help_price', '助力金额')->attribute('maxlength', 8)->symbol('￥')
                ->rules('required|min:0')->required();
            $form->textarea('product_content', __('shop_product.product_content'));
        });
        $form->saving(function (Form $form,) {
            if ($form->product_status == 2) {
                $form->publish_at = now()->toDateString();
            }
            if ($form->isCreating()) {
                $form->created_time = now()->toDateString();
                $form->serial_number = AdminShopProductModel::getSerialNumber();
                if (is_null($form->main_img_ids)) {
                    $form->main_img_ids = __('com.defaultImg');
                    $form->product_avatar = __('com.defaultImg');
                } else {
                    $form->product_avatar = explode(',', $form->main_img_ids)[0];
                }
            }
            if (is_null($form->product_stage)) {
                $form->product_stage = 0;
            }
            $form->product_category_id_2 = [0, 37, 32, 41][$form->ext['plug_cate']];
            $form->product_category_id_3 = [0, 39, 43, 42][$form->ext['plug_cate']];
            $form->min_price = $form->max_price;
        });
        $form->saved(function (Form $form,) {
            $userId = Admin::user()->user_id;
            $userMainId = ShopUserLogic::valueByWhere('userId', $userId, 'userMainId');
            if ($form->isCreating()) {
                $spec = ShopProductSpecsLogic::insertForModel([
                    'productId' => $form->model()->product_id,
                    'randProductId' => 0,
                    'userId' => is_null($userMainId) || $userMainId === 0 ? $userId : $userMainId,
                    'psPriceUnderlined' => $form->min_price,
                    'psTotalStock' => 1,
                    'psUsableStock' => 1,
                    'psName' => '默认',
                ]);
                cache(['shopProductSpec:'.$spec->serial_number => $spec->ps_id]);
                $form->model()->ps_id_json = $spec->ps_id;
                $form->model()->spec_json = $spec->serial_number;
                $form->model()->save();
            } else {
                ShopProductSpecsLogic::updateByWhere(['psPriceUnderlined' => $form->min_price],
                    'productId',
                    $form->model()->product_id);
            }
        });
        return $form->setWidth(10)->confirm('确定提交吗?');
    }

    /**
     * detail
     * @param  int  $id
     * @return Show
     */
    protected function detail(int $id,): Show
    {
        $show = new Show(AdminShopProductModel::findOrFail($id));
        $show->field('product_id', 'ID');
        $show->field('serial_number', __('l.serialNumber'));
        $show->field('sort', __('l.sort'));
        $show->field('product_status', __('l.status'))->using([1 => '下架', 2 => '上架']);
        $show->field('status_recommend', '推荐')->using(__('l.whether'));
        $show->field('main_img_ids', '主图')->unescape()->as(function ($column,) {
            if (empty($column)) {
                return null;
            }
            $arr = [];
            foreach (explode(',', $column) as $v) {
                $arr[] = fileIdToUrl($v);
            }
            return $arr;
        })->carousel();
        $show->field('product_name', '名称');
        $show->field('desc_img_ids', '详情图')->unescape()->as(function ($column,) {
            if (empty($column)) {
                return null;
            }
            $arr = [];
            foreach (explode(',', $column) as $v) {
                $arr[] = fileIdToUrl($v);
            }
            return $arr;
        })->carousel();
        $show->field('video_id', '视频')->unescape()->as(function ($field,) {
            if (empty($field)) {
                return null;
            } else {
                return view('video', ['url' => fileIdToUrl($field)]);
            }
        });
        $show->field('ext.plug_cate', '分类')->using(Arr::get(cache('systemConfig:1'), 'jlTag'));
        $show->field('min_price', '当前价');
        $show->field('max_price', '原价');
        $show->field('product_stock_empty', '库存')->using(__('shop_product.stockArr'));
        $show->field('ext.help_price', '助力金额');
        $show->field('created_at', __('l.createdAt'));
        return $show;
    }

    private function specSimple(): array
    {
        return [
            'ps_id' => 'ID',
            'serial_number' => '序列号',
            'fileUrl' => '图片',
            'ps_name' => '名称',
        ];
    }

    /**
     * item
     * @param  Form  $form
     * @return Model|null
     */
    private function item(Form $form,): ?Model
    {
        $item = null;
        if ($form->isEditing()) {
            $id = request()->route()->parameters()['id'] ?? request()->route()->parameters()['shopProductHelp'];
            $item = AdminShopProductModel::query()->find($id);
        }
        return $item;
    }
}
